package com.didispace;

import com.didispace.condition.LinuxCondition;
import com.didispace.condition.WindowsCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {




    //////////////////////////////////
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }


	/**
     * 配置登录的账号，密码
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
    ///////////////////////////////////////

    /////////////////////////////////////配置认证f服务器开始
	@Configuration
	@EnableAuthorizationServer
	protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

		/**
		 * 配置客户端信息
		 * @param clients
		 * @throws Exception
		 */
		@Override
		public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
			clients.inMemory().withClient("tonr").secret("secret").authorizedGrantTypes("authorization_code")
					.scopes("read");
		}


		/**
		 * 配置令牌端点(Token Endpoint)的安全约束
		 * @param security
		 * @throws Exception
		 */
		@Override
		public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
			super.configure(security);
		}


		/**
		 * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)。
		 * @param endpoints
		 * @throws Exception
		 */
		@Override
		public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
			super.configure(endpoints);
		}
	}
	/////////////////////////////////////配置认证f服务器结束


/////////////////////////////////////配置资源服务器开始

	@Configuration
	@EnableResourceServer
	protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


		@Override
		public void configure(ResourceServerSecurityConfigurer resources) {
			resources.resourceId("app").stateless(false);
		}

		@Override
		public void configure(HttpSecurity http) throws Exception {
			http
					.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
					.and()
					.requestMatchers().antMatchers("/se")
					.and()
					.authorizeRequests()
					.antMatchers("/se").access("#oauth2.hasScope('read')");
		}

	}
	/////////////////////////////////////配置资源服务器结束



	//测试按条件初始化bean开始
    @Bean
    @Conditional(LinuxCondition.class)
    public String testLinux(){
        System.out.println("fsfsf");
        return "linux";
    }

    @Bean
    @Conditional(WindowsCondition.class)
    public String testWindow(){
        System.out.println("fsfsf");
        return "windows";
    }
	//测试按条件初始化bean结束

}